package cn.shyouchi.wuguanjia.android.ui.event.check;

import android.app.DialogFragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.iasii.app.citylist.entity.City;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.controls.BasicEditDialogFragment;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.AMapUtil;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.R.id.topBar;

public class EventCheckActivity extends BaseActivity implements EventCheckContract.View, AMapLocationListener,
        GeocodeSearch.OnGeocodeSearchListener {
    @BindView(R.id.map)
    MapView mMapView = null;
    @BindView(topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_check_event)
    RecyclerView mRvCheckEvent;

    List<EventCheckModel> mCheckModels = new ArrayList<>();
    EventCheckAdapter mCheckAdapter;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    AMapLocationClientOption mLocationClientOption;

    Marker mLocationMarker;

    Marker mCheckPointMarker;

    AMap mMap;

    EventCheckModel pointModel;

    GeocodeSearch mGeocodeSearch;

    //考勤范围
    Circle mLocationCircle;


    EventApi mEventApi;

    String projectId;

    boolean isLocationed = false;
    double radius = 0d;

    boolean isEdit = false;

    int id = 0;

    String searchCity = "";

    String locCity = "";


    @Override

    public int initContentView() {
        return R.layout.activity_event_ckeck;
    }

    @Override
    public void initInjector() {
        mGeocodeSearch = new GeocodeSearch(this);
        mGeocodeSearch.setOnGeocodeSearchListener(this);
        mEventApi = new EventApi(mContext);
        projectId = getIntent().getStringExtra("projectId");


    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        initModel();
        mCheckAdapter = new EventCheckAdapter(mCheckModels, this);
        mRvCheckEvent.setLayoutManager(new LinearLayoutManager(mContext));
        mRvCheckEvent.setAdapter(mCheckAdapter);
        EventBus.getDefault().register(this);

        initLocation();


    }

    private void initModel() {
        mCheckModels.add(new EventCheckModel(EventCheckModel.EVENT_CHECK_TYPE_CITY, "签到城市", "", InputType.TYPE_CLASS_TEXT));
        mCheckModels.add(new EventCheckModel(EventCheckModel.EVENT_CHECK_TYPE_POINT, "签到地址", "请输入签到地址", InputType.TYPE_CLASS_TEXT));
        mCheckModels.add(new EventCheckModel(EventCheckModel.EVENT_CHECK_TYPE_RANK, "考勤范围", "请输入考勤范围", InputType.TYPE_CLASS_NUMBER));
        mCheckModels.add(new EventCheckModel(EventCheckModel.EVENT_CHECK_TYPE_COUNT, "考勤天数", "请输入考勤天数，如：26天", InputType.TYPE_CLASS_NUMBER));
        mCheckModels.add(new EventCheckModel(EventCheckModel.EVENT_CHECK_TYPE_FINGER, "提示指纹录入时间", "请输入指纹录入时间，如：26天", InputType.TYPE_CLASS_NUMBER));
        mCheckModels.add(new EventCheckModel(EventCheckModel.EVENT_CHECK_TYPE_SIGN, "提示签合同时间", "请输入签合同时间，如：26天", InputType.TYPE_CLASS_NUMBER));
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取地图控件引用
        mMapView.onCreate(savedInstanceState);

        if (mMapView != null) {
            mMap = mMapView.getMap();
        }


//        if (fetchLastLocation() != null) {
//            LatLng latLng = new LatLng(fetchLastLocation().getLatitude(), fetchLastLocation().getLongitude());
//            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
//            MarkerOptions markerOptions = new MarkerOptions();
//            markerOptions.position(latLng);
//            markerOptions.title("我的位置");
//            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_marker));
//            mLocationMarker = mMap.addMarker(markerOptions);
//        }


    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();


    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }


    private synchronized void showFieldEditDialog(IBaseModel baseModel) {
        final EventCheckModel model = (EventCheckModel) baseModel;
        BasicEditDialogFragment dialog = BasicEditDialogFragment.newInstance(model.getName(), model.getHint(), model.getInputType(), model.isMultiLines());
        dialog.setEnterClickListener(new BasicEditDialogFragment.BasicEditDialogListener() {
            @Override
            public void onBasicEditDialogPositiveClick(DialogFragment dialog, String content) {
                if (model.getType() == EventCheckModel.EVENT_CHECK_TYPE_POINT) {
                    searchPoi(content, model);
                    pointModel = model;
                    model.setValue(content);


                } else if (model.getType() == EventCheckModel.EVENT_CHECK_TYPE_RANK) {

                    model.setValue(content);
                    onRangeChange(Integer.parseInt(content));
                    mCheckAdapter.notifyDataSetChanged();
                } else {
                    model.setValue(content);
                    mCheckAdapter.notifyDataSetChanged();
                }
            }
        });
        dialog.show(getFragmentManager(), "CompanyEditDialogFragment");
    }

    @Override
    public void infoItemClick(IBaseModel baseModel) {

        if (isLocationed) {
            EventCheckModel model = (EventCheckModel) baseModel;
//        if (model.getType() == EventCheckModel.EVENT_CHECK_TYPE_POINT) {
//
//            pointModel = model;
//            generateEntity();
//        } else {

            if (model.getType() != EventCheckModel.EVENT_CHECK_TYPE_CITY) {
                showFieldEditDialog(model);
            } else {

                Intent intent = new Intent(mContext, ChooseCityActivity.class);
                intent.putExtra("city", locCity);
                startActivity(intent);

            }
        } else {
            ToastUtil.showToast("请等待定位完成");
        }


//        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("保存");
        menuItem.setShowAsAction(2);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("保存")) {
            generateEntity();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void generateEntity() {
        String address = "";
        String attendance = "";
        String attendancescope = "";
        String fingerprinttime = "";
        String contracttime = "";
        boolean filled = true;
        for (EventCheckModel model : mCheckModels) {
            switch (model.getType()) {
                case EventCheckModel.EVENT_CHECK_TYPE_POINT:
                    if (!TextUtils.isEmpty(model.getValue())) {
                        address = model.getValue();
                    } else {
                        filled = false;
                        ToastUtil.showToast("请填写考勤地址");
                        return;
                    }

                    break;
                case EventCheckModel.EVENT_CHECK_TYPE_CITY:
//                    if (!TextUtils.isEmpty(model.getValue())) {
//                        attendance = model.getValue();
//                    } else {
//                        filled = false;
//                        ToastUtil.showToast("请选择考勤城市");
//                        return;
//                    }
                    break;
                case EventCheckModel.EVENT_CHECK_TYPE_COUNT:
                    if (!TextUtils.isEmpty(model.getValue())) {
                        attendancescope = model.getValue();
                    } else {
                        filled = false;
                        ToastUtil.showToast("请填写考勤天数");
                        return;
                    }
                    break;

                case EventCheckModel.EVENT_CHECK_TYPE_FINGER:
                    if (!TextUtils.isEmpty(model.getValue())) {
                        fingerprinttime = model.getValue();
                    } else {
                        filled = false;
                        ToastUtil.showToast("请填写指纹录入时间");
                        return;
                    }
                    break;

                case EventCheckModel.EVENT_CHECK_TYPE_SIGN:
                    if (!TextUtils.isEmpty(model.getValue())) {
                        contracttime = model.getValue();
                    } else {
                        filled = false;
                        ToastUtil.showToast("请填写签合同时间");
                        return;
                    }
                    break;
            }
        }
        if (mCheckPointMarker != null && mCheckPointMarker.getPosition() != null && filled) {

            if (isEdit) {
                mEventApi.upCheck(projectId,
                        searchCity,
                        address,
                        attendancescope,
                        String.valueOf(radius),
                        fingerprinttime,
                        contracttime,
                        String.valueOf(mCheckPointMarker.getPosition().longitude),
                        String.valueOf(mCheckPointMarker.getPosition().latitude))
                        .subscribeOn(Schedulers.io())
//                        .compose(RxLifecycle.bindUntilEvent(bindLife(), ActivityEvent.DESTROY))
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                            @Override
                            public void onNext(BaseRequestResult result) {
                                finish();
                            }
                        });

            } else {
                mEventApi.addCheck(projectId,
                        searchCity,
                        address,
                        attendancescope,
                        String.valueOf(radius),
                        fingerprinttime,
                        contracttime,
                        String.valueOf(mCheckPointMarker.getPosition().longitude),
                        String.valueOf(mCheckPointMarker.getPosition().latitude))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                            @Override
                            public void onNext(BaseRequestResult result) {
                                finish();
                            }
                        });
            }

        } else {
            ToastUtil.showToast("没有设置考勤点");
        }
    }


    private void searchPoi(String name, EventCheckModel model) {
// name表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode
        GeocodeQuery query = new GeocodeQuery(name, mCheckModels.get(0).getValue());

        mGeocodeSearch.getFromLocationNameAsyn(query);
    }


    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        LogUtil.json(result);

        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                String addressName = result.getRegeocodeAddress().getFormatAddress()
                        + "附近";

                LogUtil.e(addressName);


                pointModel.setValue(addressName);
                mCheckAdapter.notifyItemChanged(0);

//                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
//                        AMapUtil.convertToLatLng(latLonPoint), 15));
//                regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
//                ToastUtil.showToast( addressName);
            } else {
//                ToastUtil.show(ReGeocoderActivity.this, R.string.no_result);
            }
        } else {
//            ToastUtil.showerror(this, rCode);
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult result, int code) {
        LogUtil.json(result);
        List list = result.getGeocodeAddressList();

        if (list == null || list.isEmpty()) {

            ToastUtil.showToast("没有合适的结果");

        } else if (list.size() == 1) {
            turnPointAndMark(result.getGeocodeAddressList().get(0).getLatLonPoint());
        } else {
            ToastUtil.showToast("有多个结果，请更换精确地关键词");
        }
        mCheckAdapter.notifyDataSetChanged();
    }


    private void turnPointAndMark(LatLonPoint latLng) {
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(AMapUtil.convertToLatLng(latLng), 16));
        onLatLngChange(AMapUtil.convertToLatLng(latLng));
    }


    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClientOption = new AMapLocationClientOption();


        //设置定位回调监听
        mLocationClient.setLocationListener(this);

        //设置定位一次、该方法默认为false。
        mLocationClientOption.setOnceLocation(true);

        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationClientOption.setOnceLocationLatest(true);

        mLocationClient.setLocationOption(mLocationClientOption);
        mLocationClient.startLocation();
    }


    @Override
    public void onLocationChanged(final AMapLocation location) {
        LogUtil.json(location);
        if (location != null && location.getErrorCode() == 0) {

            locCity = location.getCity();

            LatLng lng = new LatLng(location.getLatitude(), location.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(lng)
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_marker));
            isLocationed = true;
            if (mLocationMarker == null) {
                mLocationMarker = mMap.addMarker(markerOptions);

                mLocationCircle = mMap.addCircle(new CircleOptions()
                        .center(lng)
                        .radius(radius)
                        .fillColor(Color.parseColor("#503B3231"))
                        .strokeColor(Color.parseColor("#504996FF"))
                        .strokeWidth(5));
            } else {
                mLocationMarker.setPosition(lng);
            }
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lng, 16));


            mEventApi.getCheckList(projectId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<CheckEntity>(mContext) {
                        @Override
                        public void onNext(CheckEntity entity) {
                            isEdit = true;


                            if (TextUtils.isEmpty(entity.getResultMessage().getArea())) {
                                setSearchCity(location.getCity());
                            } else {
                                setSearchCity(entity.getResultMessage().getArea());
                            }
                            mCheckModels.get(1).setValue(entity.getResultMessage().getAddress());
                            mCheckModels.get(2).setValue(entity.getResultMessage().getAttendancescope());
                            mCheckModels.get(3).setValue(entity.getResultMessage().getAttendance());
                            mCheckModels.get(4).setValue(entity.getResultMessage().getFingerprinttime());
                            mCheckModels.get(5).setValue(entity.getResultMessage().getContracttime());
                            onLatLngChange(new LatLng(Double.parseDouble(entity.getResultMessage().getLatitude()), Double.parseDouble(entity.getResultMessage().getLongitude())));
                            mCheckAdapter.notifyDataSetChanged();
                        }
                    });

        }
    }

    @Override
    public void onRangeChange(double radius) {
        this.radius = radius;
        mLocationCircle.setRadius(radius);
    }

    @Override
    public boolean isSetPoint() {
        return mCheckPointMarker != null;
    }

    public void onLatLngChange(LatLng lng) {
        if (mCheckPointMarker == null) {
//            onRangeChange(0);

            MarkerOptions markerOptions = new MarkerOptions()
                    .position(lng)
                    .title("考勤点")
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_check_point_mark));
            mCheckPointMarker = mMap.addMarker(markerOptions);
            mCheckPointMarker.showInfoWindow();
        } else {
            mCheckPointMarker.setPosition(lng);
        }

        mCheckPointMarker.setPosition(lng);
        mLocationCircle.setCenter(lng);
    }


    /**
     * 设置地图搜索的城市
     *
     * @param city
     */
    public void setSearchCity(String city) {
        mCheckModels.get(0).setValue(city);
        searchCity = city;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCityChange(City city) {
        LogUtil.e(city.getName());
        setSearchCity(city.getName());
        mCheckModels.get(1).setValue("");
        mCheckAdapter.notifyDataSetChanged();
    }


    public AMapLocation fetchLastLocation() {
        return mLocationClient.getLastKnownLocation();
    }


}
